package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
@Order(1)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、是否是登录
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if (url.contains("/login/in")){
            return chain.filter(exchange);
        }
        try {
            //2、token是否为空
            String jwtToken = request.getHeaders().getFirst("token");
            if (StringUtils.isBlank(jwtToken)){
              //如果为空则说明是非法登录，则拦截,返回错误信息
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //3、token是否过期
            //过期则拦截
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int verifyToken = AppJwtUtil.verifyToken(claims);
            if (verifyToken>0){
                //verifyToken>0 说明token过期了
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //4、把用户信息从token中拿出来，并设置id到header中
            //解析jwt令牌
            Integer id = claims.get("id", Integer.class);
            //打印日志
            log.info("Header token id:{},url:{}",id,url);

            //5、把token传到各个微服务中
            ServerHttpRequest serverHttpRequest = request.mutate()
                    .headers(httpHeaders ->{
                            httpHeaders.add("userId", id.toString());
                    }).build();

            exchange.mutate().request(serverHttpRequest).build();
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6、放行
        return chain.filter(exchange);
    }
}
